package cn.acheng1314.utils
import org.apache.commons.lang3.StringUtils
import java.math.BigInteger
import java.util.*


object EncryptUtils : HashKit() {
    fun salt(): String {
        val random = (10 + Math.random() * 10).toInt()
        return UUID.randomUUID().toString().replace("-", "").substring(random) // 随机长度
    }

    fun encryptPassword(password: String, salt: String): String {
        return if (!StringUtils.isEmpty(salt)) //加盐
        {
            sha256(password + salt)
        } else {
            sha256(password)
        }
    }

    fun verlifyUser(userPassword: String?, userSalt: String?, password: String): Boolean {
        if (userPassword == null) return false
        return if (userSalt == null) {
            false
        } else userPassword == encryptPassword(password, userSalt)
    }

    fun generateUcode(id: BigInteger, salt: String): String {
        return md5(id.toString() + salt)
    }

    fun signForRequest(params: Map<String, String?>, secret: String?): String {
        val keys = params.keys.toTypedArray()
        Arrays.sort(keys)
        val query = StringBuilder()
        query.append(secret)
        for (key in keys) {
            val value = params[key]
            if (StringUtils.isNoneBlank(key, value)) {
                query.append(key).append(value)
            }
        }
        query.append(secret)
        return md5(query.toString()).toUpperCase()
    }
}
